package com.turing.data.scripts.yhlc.filter

import com.alibaba.fastjson.JSON
import com.turing.common.entity.TextVO
import com.turing.common.util.FileUtils
import com.turing.common.util.StringUtils
import com.turing.data.engine.TextUtils
import com.turing.data.engine.utils.ScriptsUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import org.apache.commons.lang.SerializationUtils
import com.turing.data.engine.utils.RegexExtract

/**
 * @description: 银行理财 - 成交金额
 * @author: mazhishen
 */

class Amount_30252_46_filter {

    static List< TaskElementVO.DrawResultVO > doConvert(DependParamsVO dependParams){
        def REGEX_BACKUP = "该期信托资金金额"
        def REGEX_BACKUP_2 = "确认"
        def REGEX_BACKUP_3 = "赎回"
        def REGEX_BACKUP_4 = "申购"
        def REGEX_BACKUP_5 = "￥"

        List< TaskElementVO.DrawResultVO > trueValueSet = new ArrayList<>()
        List<TaskElementVO.DrawResultVO > resultVOs = ScriptsUtils.tryInitResult(dependParams)
        def set = new HashSet()
        if (resultVOs!=null && resultVOs.size()>0) {
            for (int i = 0; i < resultVOs.size(); i++) {
                def drawResultVO = resultVOs.get(i)
                def childTaskSn = drawResultVO.childTaskSn
                if(null == childTaskSn || childTaskSn == ""){
                    return resultVOs
                }
                def start = drawResultVO.start
                def end = drawResultVO.end
                def text = drawResultVO.text
                text = text.replaceAll("\n","")
                def textPathMap = dependParams.textPathMap
                def rawPath = textPathMap.get(drawResultVO.childTaskSn)
                def rawText = FileUtils.loadJson(rawPath)
                def expandOffset = 0
                //往前10个字符搜索
                while( expandOffset < 20 && start > expandOffset ){
                    def expandString = rawText.substring(start-expandOffset,start)
                    if( expandString =~ REGEX_BACKUP
                        || expandString =~ REGEX_BACKUP_2
                        || expandString =~ REGEX_BACKUP_3
                        || expandString =~ REGEX_BACKUP_4
                        || expandString =~ REGEX_BACKUP_5
                    )
                    {
                        drawResultVO.text = drawResultVO.text.replaceAll(/[，]/,",")
                        drawResultVO = getAmountSmall(drawResultVO)
                        trueValueSet.add(drawResultVO)
                        set.add(drawResultVO.text)
                        return trueValueSet
                    }
                    expandOffset ++
                }
            }
        }

        String childTaskId = ""

        try{
            if(trueValueSet.size()==0){

                String REGEX = /(人民币|(小写)).{1,30}元/
                println dependParams.JSONTextMap.size()
                dependParams.JSONTextMap.forEach(
                        { childTaskSn, jsonText ->
                            childTaskId = childTaskSn
                            RegexExtract.doRuleExtract(REGEX,childTaskSn, dependParams, jsonText, trueValueSet)
                        }
                )

                if(trueValueSet.size()>0){
                    def textPathMap = dependParams.textPathMap
                    def childTaskSn = trueValueSet[0].childTaskSn
                    def rawPath = textPathMap.get(childTaskSn)
                    def rawText = FileUtils.loadJson(rawPath)
                    def JSONTextMap = dependParams.JSONTextMap
                    def fileTextStr = ""
                    fileTextStr = JSONTextMap.get(childTaskSn)
                    def text = trueValueSet[0].text
                    def index = text.indexOf("￥")
                    if( index == -1){
                        index = text.indexOf("币")
                    }else if( index == -1){
                        index = text.lastIndexOf(")")
                    }
                    def startOffset = index + 1
                    def endOffset = -"元".length()
                    TaskElementVO.DrawResultVO objectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(trueValueSet[0])
                    objectNew = TextUtils.correctPositionInfoByOffset(objectNew, startOffset, endOffset, fileTextStr, rawText)
                    trueValueSet.clear()
                    trueValueSet.add(objectNew)
                    return trueValueSet
                }
            }
        }
        catch (Exception e){
            e.printStackTrace()
        }

        //处理关键词和对应的值跨行问题：20210802-惠享添利赎回确认书
        try {
            String REGEX0 = /(申购.{0,1}金额|认购.{0,1}信托资金|赎回.{0,1}金额|赎回.{0,1}信托资金)/
            def resultMatcherList = matching(dependParams,REGEX0,-7)
            if(resultMatcherList.size()>0){
                TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
                //默认结果选第一个,对正则后的内容进行处理
                def originalText = resultMatcherList[0].objContent
                def getFinalReg = /\d.+?\d(?=元)/
                //处理返回的文本
                def matcherText = originalText =~ getFinalReg
                def finalText = originalText
                if(matcherText.count>0){finalText = matcherText[0]}
                //设置返回的文本
                defaultDrawResultVO.text = finalText
                defaultDrawResultVO.businessValue = defaultDrawResultVO.text
                defaultDrawResultVO.childTaskSn = childTaskId
                defaultDrawResultVO.para_info  =  [resultMatcherList[0].lineId]
                //处理返回文本高亮
                //将处理后的正则结果和原来该行的所有内容进行正则匹配，找出起始位置，默认全文
                def positionMatcher = resultMatcherList[0].objContent =~ getFinalReg
                def positionStart = 0
                def positionEnd = originalText.length()
                while (positionMatcher.find()){
                    positionStart = positionMatcher.start()
                    positionEnd = positionMatcher.end()
                }
                defaultDrawResultVO.businessValue = defaultDrawResultVO.text.replaceAll(/[，]/,",")
                defaultDrawResultVO.type = 1
                defaultDrawResultVO.pos_info = [positionStart,positionEnd]
                trueValueSet.clear()
                trueValueSet.add(defaultDrawResultVO)
                return  trueValueSet
            }
        } catch (Exception e1) {
            e1.printStackTrace()
        }


        //如果过滤后没有值，那么就默认返回模型给的第一个值
        if(trueValueSet.size() == 0 && resultVOs.size() > 0 && !StringUtils.isEmpty(resultVOs[0].text)){
            trueValueSet.add(resultVOs[0])
            return  trueValueSet
        }

        TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
        defaultDrawResultVO.text = ""
        trueValueSet.add(defaultDrawResultVO)
        return  trueValueSet

    }


    //通过正则获得一行内容
    static List<TextVO.Line> matching(DependParamsVO dependParams, String reg, int step){
        //返回结果的集合
        List<TextVO.Line> resultMatcherList = new ArrayList<>()
        //表格类型：通过json文本找到关键词的所在行
        dependParams.getJSONTextMap().forEach({ childTaskSn, jsonText ->
            List<TextVO> textVOList = JSON.parseArray(jsonText, TextVO.class)
            for (i in 0..<textVOList.size()) {
                //获得段落列表
                List<TextVO.Paragraph> listParagraph = textVOList[i].paragraphs
                for (j in 0..<listParagraph.size()) {
                    //获得每行的具体信息
                    List<TextVO.Line> lines = listParagraph[j].lines
                    for (k in 0..<lines.size()) {
                        //每行内容匹配关键词
                        def keyWordMatcher = lines[k].objContent =~ reg
                        if (keyWordMatcher.count > 0) {
                            //结果对象，关键词的下一局
                            resultMatcherList.add(lines[k + step])
                        }
                    }
                }
            }
        })
        return resultMatcherList
    }

    //处理金额
    static TaskElementVO.DrawResultVO getAmountSmall (TaskElementVO.DrawResultVO  drawResultVO){
        //对未处理的小写金额进行处理
        if(drawResultVO.text.contains(",") && drawResultVO.text.contains(".")){
            return drawResultVO
        }else{
            String modelValue = drawResultVO.text.replaceAll(/[,，.]/,"")
            def result = ""
            //获得末尾两个数字
            def last = modelValue.substring(modelValue.length()-2,modelValue.length())
            //除去末尾两个数字
            def str2 = modelValue.substring(0,modelValue.length()-2)
            // 逆转
            def str3 = str2.reverse()
            //转化为数组进行遍历
            def arr = str3.toCharArray()
            //定义一个空字符串
            def ture = ""
            def num = 0
            for (i in arr) {
                num++
                if(num%3==0&&num!=arr.length){
                    println ("num"+num)
                    ture = ture+i+","
                }else{
                    ture = ture+i
                }
            }
            //进行反转 和 加上末尾两个数字
            result = ture.reverse().concat("."+last)
            drawResultVO.businessValue = result
            drawResultVO.type = 1
            return drawResultVO
        }
    }

}
